<template>
    <div class="workorder">
        <div class="page-head">
            <span class="head-text">入库小程序</span>
            <span class="head-text">当前用户：{{ userInfo.username }}</span>
        </div>
        <div class="page-radio">
            <div class="radio-head">
                <el-radio-group v-model="workshop">
                    <el-radio :label="1">机加工</el-radio>
                    <el-radio :label="2">走心机</el-radio>
                    <el-radio :label="3">EPC</el-radio>
                </el-radio-group>
            </div>
            <div class="radio-content" v-show="workshop === 1 || workshop === 2">
                <span class="content-tip">工序:</span>
                <div class="content-process">
                    <el-radio-group v-model="workshopProcess">
                        <el-radio v-show="workshop === 1" label="A" class="process-item">热处理</el-radio>
                        <el-radio v-show="workshop === 1" label="B" class="process-item">清洗机</el-radio>
                        <el-radio v-show="workshop === 2" label="C" class="process-item">清洗机</el-radio>
                    </el-radio-group>
                </div>
            </div>
        </div>
        <div class="page-main">
            <div class="main-left">
                <el-form :model="formData" ref="leftForm" :rules="formDataRules" label-width="100px" label-position="left" size="mini" hide-required-asterisk class="demo-ruleForm">
                    <el-form-item label="品号" prop="materialCode">
                        <el-select v-model="formData.materialCode" filterable remote :remote-method="remoteMethod" clearable placeholder="下拉选择产品" size="small" transfer="true" :popper-append-to-body="false">
                            <el-option v-for="(item,index) in materialCodeList" :label="item" :value="item" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="订单" prop="productOrder">
                        <el-select v-model="formData.productOrder" placeholder="下拉选择订单" size="small">
                            <el-option v-for="item,index in formData.productOrderList" :label="item.productOrderNumber" :value="item.productOrderNumber" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="入库时间" prop="datetime" size="small">
                        <el-date-picker v-model="formData.entryDatetime" :editable="false" type="date" value-format="yyyy-MM-dd HH:mm:ss" size="small" placeholder="选择日期时间" class="el-date-picker"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="申请人" size="small">
                        <el-input :value="userInfo.username" placeholder="自动读取当前用户" :disabled="true"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div class="main-right">
                <el-form :model="formData" ref="rightForm" :rules="formDataRules" label-width="100px" label-position="left" size="mini" hide-required-asterisk class="demo-ruleForm">
                    <el-form-item label="计划数量" size="small">
                        <el-input :value="formData.planNumber" placeholder="自动读取" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="完成数量" prop="finishedNum">
                        <el-input v-model="formData.finishedNum" @input="formData.finishedNum = String(formData.finishedNum).replace(/[^\d]/g, '')" size="small" placeholder="请输入完成数量"></el-input>
                    </el-form-item>
                    <el-form-item label="不合格数" prop="unQualifiedNum" size="small">
                        <el-input v-model="formData.unQualifiedNum" @input="formData.unQualifiedNum = String(formData.unQualifiedNum).replace(/[^\d]/g, '')" size="small" placeholder="请输入不合格数量"></el-input>
                    </el-form-item>
                    <el-form-item label="合格数量" size="small">
                        <el-input :value="qualifiedNum"  placeholder="自动计算" :disabled="true"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="page-footer">
            <el-button type="primary" size="small" class="footer-btn" @click="cancel_btn">取消</el-button>
            <el-button type="primary" size="small" class="footer-btn" @click="save_btn">入库</el-button>
        </div>
    </div>
</template>
  
<script>
import { reqUserInfo, reqProductOrderList, reqMaterialsInfo } from "@/api/workOrder.js";
import { reqMaterialListByGrid, reqEntryWarehouse } from "@/api/warehouseEntry.js";
import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
export default {
    name:"warehouseEntry",
    data() {
        var validate1 = (rule, value, callback) => {
            let unQualifiedNum = this.formData.unQualifiedNum;
            if (value === '') {
                callback(new Error('请输入合格数量'));
            } else if (parseInt(value < 0)) {
                callback(new Error('输入的数量非法'));
            } else if(unQualifiedNum !== '' && parseInt(value) < parseInt(unQualifiedNum)){
                callback(new Error('完成数量不能小于不合格数量'));
            } else {
                callback();
            }
        };
        var validate2 = (rule, value, callback) => {
            let finishedNum =  this.formData.finishedNum;
            if (value === '') {
                callback(new Error('请输入不合格数量'));
            } else if (parseInt(value < 0)) {
                callback(new Error('输入的不合格数量非法'));
            } else if(finishedNum !== '' && parseInt(value) > parseInt(finishedNum)){
                callback(new Error('输入的不合格数量不能大于完成数量'));
            } else {
                callback();
            }
        };
        return {
            userInfo:{
                username:"",
                userId:"",
                userPhone:"",
                user:"",
                classTeamList:[]
            },
            workshop:1,  //车间 1机加工、2走心机、3走心机
            workshopProcess:"",
            formData:{
                materialCode:"",
                productOrder:"",
                entryDatetime:this.formatDate(new Date(),0),
                planNumber:"",
                finishedNum:"",
                unQualifiedNum:"",
                qualifiedNum:"",
                materialList:[],
                materialRemoteList:[],
                productOrderList:[],
            },
            formDataRules:{
                materialCode:[{required:true, message:"请选择产品", trigger: 'change'}],
                productOrder:[{required:true, message:"请选择订单", trigger: 'change'}],
                entryDatetime: [{ required: true, message: '请选择报工时间', trigger: 'blur'}],
                finishedNum: [{ validator: validate1, trigger: 'blur' }],
                unQualifiedNum:[{ validator: validate2, trigger: 'blur' }]
            }
        };
    },
    mounted(){
        this.getMaterialListByGrid();
        //精致环境下进行自动转屏
        autoOrientation();
        //精致平台获取用户信息可能不准,此函数需要延迟调用
        setTimeout(()=> {
            this.getUserInfo();
        },300)
        document.title = "入库小程序";
    },
    computed:{
        qualifiedNum(){
            let finishedNum = this.formData.finishedNum;
            let unQualifiedNum = this.formData.unQualifiedNum;
            if( finishedNum !== '' && unQualifiedNum !== '' && parseInt(unQualifiedNum) >= 0 && parseInt(finishedNum) >= parseInt(unQualifiedNum)){
                const number = parseInt(finishedNum) - parseInt(unQualifiedNum);
                this.formData.qualifiedNum = number;
                return number;
            }
            return '';
        },
        materialCodeList(){
            const materialList = this.formData.materialList;
            const materialRemoteList = this.formData.materialRemoteList;
            if(materialRemoteList.length > 0){
                return materialRemoteList;
            } else {
                return materialList;
            }
        }
    },
    watch:{
        workshop:{
            handler(newValue,oldValue){
                this.getMaterialListByGrid();
                this.formData.materialCode = "";
            }
        },
        "formData.materialCode":{
            handler(newVal, oldVal){
                if(newVal !== oldVal && newVal !== ""){
                    this.formData.productOrder = "";
                    this.getProductOrderList();
                }
                if(newVal === "" || newVal === null){
                    this.formData.productOrder = "";
                    this.formData.materialRemoteList = [];
                }
            }
        },
        //监听订单的选择
        "formData.productOrder":{
            handler(newVal, oldVal){
                if(newVal !== oldVal && newVal !== ""){
                    //获取订单中的计划数量
                    const orderInfo = this.formData.productOrderList.find(item => item.productOrderNumber === this.formData.productOrder);
                    this.formData.planNumber = orderInfo.productOrderMaterials[0].planQuantity;
                }
                if(newVal === ""){
                    this.formData.planNumber = "";
                }
            }
        }
    },
    methods: {
        //获取当前用户信息
        async getUserInfo () {
            reqUserInfo().then(res => {
                if(res.data.code === 200){
                    this.userInfo.username = res.data.data.nickname;
                    this.userInfo.userId = res.data.data.id;
                    this.userInfo.userPhone = res.data.data.mobile;
                    this.userInfo.user = res.data.data.username;
                }
                console.log("获取当前用户信息",res);
            }).catch(err => {
                this.$message({type:"error",message:"网络异常，用户信息获取失败"});
            })
        },
        getMaterialListByGrid(){
            const workshop = this.workshop;
            let grid = 143534;
            if(workshop === 1){
                grid = 143533;
            } else if (workshop === 2){
                grid = 143532;
            } else if (workshop === 3){
                grid = 143534;
            }
            reqMaterialListByGrid(grid).then(response => {
                if(response.data.code === 200){
                    this.formData.materialList = response.data.data;
                }
                console.log('通过车间获取物料信息',response);
            }).catch(error => {
                this.$message({type:"error",message:"物料信息获取失败"});
                console.log('通过车间获取物料信息',error);
            })
        },
        //选择号物料后查询订单信息
        async getProductOrderList () {
            const materialCode = this.formData.materialCode;
            if(materialCode === "") return ;
            reqProductOrderList(materialCode).then(res => {
                if(res.data.code === 200){
                    this.formData.productOrderList = res.data.data.content;
                }
                console.log("通过物料编码/品名查询订单信息",res);
            }).catch(err => {
                this.$message({type:"error",message:"订单信息获取失败"});
            })
        },
        async save_btn(){
            const workshop = this.workshop;
            const workshopProcess = this.workshopProcess;
            if(workshop === "") return this.$message({type:"info",message:"请选择车间类型"});
            if((workshop === 1 || workshop === 2) && workshopProcess === "") return this.$message({type:"info",message:"请选择工序"});
            let validateResult1 = false;
            let validateResult2 = false;
            this.$refs.leftForm.validate((valid) => {
                if (valid) {
                    validateResult1 = true;
                } else {
                    validateResult1 = false;
                    return false;
                }
            });
            this.$refs.rightForm.validate((valid) => {
                if (valid) {
                    validateResult2 = true;
                } else {
                    validateResult2 = false;
                    return false;
                }
            });
            if(!(validateResult1 && validateResult2)) return ;
            //准备参数
            const { userId,username,userPhone,user } = this.userInfo;
            const { materialCode,productOrder,entryDatetime,planNumber,finishedNum,unQualifiedNum,qualifiedNum } = this.formData;
            let remarkStr = "";
            if(workshop === 1){
                if(workshopProcess === 'A'){
                    remarkStr = "机加工 热处理";
                } else if(workshopProcess === 'B'){
                    remarkStr = "机加工 清洗机";
                }
            } else if(workshop === 2){
                remarkStr = "走心机 清洗机";
            } else if(workshop === 3){
                remarkStr = "EPC";
            }
            const paramsObj = {
                productCode:materialCode,
                productNumber:productOrder,
                plannedQuantity:planNumber,
                completedQuantity:finishedNum,
                qualifiedQuantity:qualifiedNum,
                unqualifiedQuantity:unQualifiedNum,
                operatorId:userId,
                operator:username,
                operatorPhone:userPhone,
                username:user,
                reportRemark:remarkStr,
                createdDate:entryDatetime
            }
            reqEntryWarehouse(paramsObj).then(response => {
                if(response.data.code === 200){
                    this.$message({type:"success",message:"入库成功"});
                    this.cancel_btn();
                }
                console.log('入库api',response);
            }).catch(error => {
                this.$message({type:"error",message:"入库失败"});
                console.log('入库api',error);
            })
        },
        cancel_btn(){
            this.$refs.leftForm.resetFields();
            this.$refs.rightForm.resetFields();
        },
        //格式化时间
        formatDate(val,type){
            let date = new Date(val);
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let h = date.getHours();
            let m = date.getMinutes();
            let s = date.getSeconds();
            if(type === 0){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 1){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day);
            } else if (type === 2){
                return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 3){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
            }
        },
        addZero(val){
            return val > 9 ? val : "0" + val;
        },
        //品名搜索
        remoteMethod(value){
            console.log(value);
            if(value.trim() === "") {
                this.formData.materialRemoteList = [];
                return;
            }
            reqMaterialsInfo(value).then(response => {
                if(response.data.code === 200 && response.data.data !== null){
                    let { code, id, name } = response.data.data.materialFields;
                    this.formData.materialRemoteList = [code];
                }
                if(response.data.code === 200 && response.data.data === null){
                    this.formData.materialRemoteList = [];
                }
                console.log('根据物料编号查询物料',response);
            }).catch(error => {
                this.$message({type:"error",message:error});
            })
        },
    },
}
</script>
  
<style lang="scss" scoped>
  .workorder{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    user-select: none;
    overflow: auto;
    .page-head{
        width: 100%;
        flex: 0.5;
        padding: 0 5%;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #4095e5;
        color: white;
        font-size: 14px;
        min-height: 40px;
    }
    @media screen and (min-width:300px) and (max-width:600px) {
        .page-head{
            width: 100%;
            height: 80px;
            align-items: flex-end;
            padding: 1% 5%;
            min-height: 100px;
        }
    }
    .page-main{
        width: 100%;
        flex: 5;
        display: flex;
        flex-wrap: wrap;
        padding: 1% 3% 0 3%;
        justify-content: space-between;
        box-sizing: border-box;
        .main-left{
            box-sizing: border-box;
        }
        .main-right{
            box-sizing: border-box;
        }
        @media screen and (min-width: 600px) {
            .main-left{
                width: 40%;
                height: 100%;
            }
            .main-right{
                width: 40%;
                height: 100%;
            }
        }
    }
    .page-radio{
        width: 100%;
        flex: 0.8;
        padding: 0.5% 3%;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        .radio-content{
            margin: 10px 0;
            display: flex;
            align-items: first baseline;
            .content-tip{
                width: 40px;
                margin-right: 15px;
                font-size: 14px;
            }
            .content-process{
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                .process-item{
                    margin-bottom: 5px;
                }
            }
        }
    }
    .page-footer{
        width: 100%;
        flex: 1;
        display: flex;
        padding: 1% 0;
        justify-content: space-evenly;
        align-items: center;
        .footer-btn{
            width: 100px;
        }
    }
  }
  //表单项
  ::v-deep .form-item{
    width: 95%;
    .el-form-item__content{
        display: flex;
        align-items: center;
    }
  }
  .el-date-picker{
    width: 70%;
  }
</style>
<style lang="scss">
@media screen and (min-width:300px) and (max-width:600px) {
    .el-message-box{
        width:320px;
    }
}
</style>